import axios from 'axios'
import { Message } from 'element-ui'
import { removeItem, getItem } from '@/utils/auth.js'

const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})
// 请求拦截
_axios.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${getItem()}`

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截
_axios.interceptors.response.use(
  (res) => {
    return res.data
  },
  (error) => {
    console.dir(error)
    if (error.response.data && error.response.data.message) {
      Message.error(error.response.data.message)
    }
    // 401统一处理  删除token,跳转至登录页
    if (error.response.status === 401) {
      removeItem()
      router.push('/login')
    }
    return Promise.reject(error)
  }
)
// 暴露
export default _axios
